/*
 * @FilePath: 08着色器-练习-旋转效果.js
 * @Author: 杜芬
 * @Date: 2024-04-22 17:18:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-30 11:39:21
 * Copyright: 2024 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 页面
 */
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
// 2. 定义全局变量 material
let scene, camera, renderer, controls, material
function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 5)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true

  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
};


function createBasic() {
  // 目标：实现旋转效果
  const geometry = new THREE.PlaneGeometry(1, 1, 64, 64)
  material = new THREE.ShaderMaterial({
    vertexShader: `
      // 4. 接收时间值-作为旋转角度
      uniform float myTime;
      void main() {
        float angle = myTime; // 旋转角度(0-360数值之间)
        float radian = radians(angle); // 角度转弧度(0-2PI)
        float cosV = cos(radian); // 求解旋转角度余弦值
        float sinV = sin(radian); // 求解旋转角度正弦值
        mat4 mx = mat4(1,0,0,0, 0,cosV,-sinV,0, 0,sinV,cosV,0, 0,0,0,1); // x 轴顺时针
        // mat4 mx = mat4(cosV,-sinV,0,0, sinV,cosV,0,0,  0,0,1,0,  0,0,0,1); // z 轴顺时针
        // mat4 mx=mat4(cosV,0,sinV,0, 0,1,0,0, -sinV,0,cosV,0, 0,0,0,1); // y 轴顺时针

        vec4 v = mx * vec4(position, 1.0);

        gl_Position = projectionMatrix * viewMatrix * modelMatrix * v;
      }
    `,
    fragmentShader: `
      void main() {
        gl_FragColor = vec4(0, 1.0, 0, 1.0);
      }
    `,
    uniforms: {
      // 1. 定义接收全局参数-时间变量值（作为旋转角度）
      myTime: {
        value: 0
      }
    },
    side: THREE.DoubleSide
  });
  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
}

function renderLoop(t) {
  // t 是毫秒级，距离最开始的时刻过了多久
  console.log(t)
  // 3. 把时间数值传入到材质的 uniforms 变量中
  material.uniforms.myTime.value = t / 10 // 为了让旋转慢一些（200 -> 20度）

  renderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
}

init()
createBasic()
renderLoop()

